package olivetv

import (
	"errors"
	"fmt"
	"net/url"
	"strings"
	"time"

	"github.com/go-olive/olive/foundation/olivetv/model"
	"github.com/go-olive/olive/foundation/olivetv/util"
	jsoniter "github.com/json-iterator/go"
)

var (
	ErrCookieNotSet = errors.New("cookie not configured")
)

func init() {
	registerSite("douyin", &douyin{})
}

type douyin struct {
	base
}

func (this *douyin) Name() string {
	return "抖音"
}

func (this *douyin) Snap(tv *TV) error {
	tv.Info = &Info{
		Timestamp: time.Now().Unix(),
	}
	return this.set(tv)
}

func (this *douyin) set(tv *TV) error {
	if tv.cookie == "" {
		return ErrCookieNotSet
	}
	req := &util.HttpRequest{
		URL:          fmt.Sprintf("https://live.douyin.com/%s", tv.RoomID),
		Method:       "GET",
		ResponseData: *new(string),
		ContentType:  "application/json",
		Header: map[string]string{
			"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36 Edg/94.0.992.38",
			"referer":    "https://live.douyin.com/",
			"cookie":     tv.cookie,
		},
	}
	var err error
	if err = req.Send(); err != nil {
		return err
	}
	resp := fmt.Sprint(req.ResponseData)
	splits := strings.Split(resp, `<script id="RENDER_DATA" type="application/json">`)
	if len(splits) < 2 {
		return fmt.Errorf("fail to find url")
	}
	resp = splits[1]
	resp = strings.Split(resp, `</script>`)[0]
	resp, err = url.QueryUnescape(resp)
	if err != nil {
		return err
	}
	var autoGenerated model.DouyinAutoGenerated
	err = jsoniter.UnmarshalFromString(resp, &autoGenerated)
	if err != nil {
		return err
	}

	// 抖音 status == 2 代表是开播的状态
	if autoGenerated.App.InitialState.RoomStore.RoomInfo.Room.Status != 2 {
		return nil
	}

	streamDataStr := autoGenerated.App.InitialState.RoomStore.RoomInfo.Room.StreamURL.LiveCoreSdkData.PullData.StreamData
	var streamData model.DouyinStreamData
	err = jsoniter.UnmarshalFromString(streamDataStr, &streamData)
	if err != nil {
		// log.Println(err.Error())
		return nil
	}
	tv.streamURL = streamData.Data.Origin.Main.Flv
	tv.roomOn = true

	tv.roomName = autoGenerated.App.InitialState.RoomStore.RoomInfo.Room.Title

	return nil
}
